package com.lotso.web.common.config;

import com.lotso.web.common.security.AjaxAuthenticationEntryPoint;
import com.lotso.web.common.security.AjaxRequestMatcher;
import com.lotso.web.common.security.CustomAuthenticationFilter;
import com.lotso.web.common.security.CustomDetailsServiceImpl;
import com.lotso.web.module.system.controller.LoginController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * ClassName: WebSecurityConfig
 * Description: Spring Security 配置
 * <p>
 * 整个SpringSecurity 的 FilterChain 基本如下：
 * <p>
 * WebAsyncManagerIntegrationFilter
 * SecurityContextPersistenceFilter
 * HeaderWriterFilter
 * LogoutFilter
 * CustomAuthenticationFilter - 自定义实现，替代了 UsernamePasswordAuthenticationFilter
 * UsernamePasswordAuthenticationFilter
 * RequestCacheAwareFilter
 * SecurityContextHolderAwareRequestFilter
 * AnonymousAuthenticationFilter - 游客
 * SessionManagementFilter
 * ExceptionTranslationFilter
 * FilterSecurityInterceptor
 * <p>
 * Date: 2017/12/27 15:40 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(4);
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        return new CustomDetailsServiceImpl();
    }

    /**
     * 配置认证授权
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(encoder());
    }

    /**
     * 忽略拦截
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/**", "/druid/**", "/global/**", "/module/**", "/pages/**", "/favicon.ico",
                "/swagger-resources/**", "/v2/api-docs", "/swagger-ui.html", "/webjars/**", "/configuration/**");
    }

    /**
     * 自定义登录拦截器
     *
     * @return
     * @throws Exception
     */
    @Bean
    public CustomAuthenticationFilter authenticationFilter() throws Exception {
        CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter();
        customAuthenticationFilter.setAuthenticationManager(super.authenticationManager());
        customAuthenticationFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error=true"));
        return customAuthenticationFilter;
    }

    /**
     * 自定义Ajax异常处理
     * {@link ExceptionTranslationFilter} 拦截器内部使用
     * 这边的 loginFormUrl 地址需要和 {@link LoginController#invalid} 的 RequestMapping 地址一致
     *
     * @return
     */
    @Bean
    public AjaxAuthenticationEntryPoint entryPoint() {
        return new AjaxAuthenticationEntryPoint("/api/ajax/authentication");
    }

    /**
     * Security 核心配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .addFilterAt(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .formLogin().loginPage("/login")
                .defaultSuccessUrl("/index", true)
                .failureUrl("/login?error=true")
                .permitAll()
                .and()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).deleteCookies("JSESSIONID")
                .invalidateHttpSession(true).permitAll()
                .and().exceptionHandling().defaultAuthenticationEntryPointFor(entryPoint(), new AjaxRequestMatcher())
                .and().csrf().disable();
    }

}
